/*
 * Questa classe gestisce i file per la gestione dell'inventario di Teatralmente Gioia
 */

/**
 * Librerie
 */
import java.io.*;
import java.util.*;

/**
 *
 * @author mattia
 * @email  mattia.angelillo@gmail.com
 */
public class Files {
    //Constant
    final String FILE = "inventory.dat";
    
    //Variables class
    DataInventory datainventory;
    DataInventory tmp;
    DataInventory temp[];
    
    //Output File
    FileOutputStream   fileOutputStream;
    ObjectOutputStream objectOutputStream;
    //Input File
    FileInputStream fileInputStream;
    ObjectInputStream objectInputStream;
    
    //Input Keyboard
    InputStreamReader input;
    BufferedReader    tastiera;
    
    //Construct
    public Files(){
        if(count()==0){
            //Creo il file se non esiste
            try {
                fileOutputStream    = new FileOutputStream(FILE);
                //objectOutputStream  = new ObjectOutputStream(fileOutputStream);

                fileOutputStream.close();
            } catch (Exception e) {}
        }
    }
    
    /**
     * Genera il codice degli elementi dell'inventario
     * @return Ritorna il codice
     */
    public int code(){
        return count()+1;
    }
    
    /**
     * Insert record into file
     */
    public void insert(){
        System.out.println("\nINSERISCI UN NUOVO ELEMENTO NELL'INVENTARIO");
        
        if(count() == 0){
            firstInsert();
        }else{
            otherInsert();
        }
    }
    
    /**
     * Insert first record
     */
    private void firstInsert(){
        System.out.println("FIRST\n");
        //Vars
        String name         = new String();
        String description  = new String();
        String category     = new String();
        int quantity        = 0;
        int code            = 1;
        
        //Se il file è vuoto
        try {
            input       = new InputStreamReader(System.in);
            tastiera    = new BufferedReader(input);

            
            //Read
            System.out.println("Nome: ");
            name = tastiera.readLine();
            System.out.println("Descrizione: ");
            description = tastiera.readLine();
            System.out.println("Categoria: ");
            category = tastiera.readLine();
            System.out.println("Quantita': ");
            quantity = Integer.valueOf(tastiera.readLine()).intValue();
            
            //Salvo i dati nella classe
            datainventory.addInventoryElement(name, description, category, quantity, code);

            //File
            try {
                fileOutputStream   = new FileOutputStream(FILE);
                objectOutputStream = new ObjectOutputStream(fileOutputStream);

                objectOutputStream.writeObject(datainventory);
                fileOutputStream.close();
            } catch (Exception e) {
                System.out.println("Eccezione: " + e.getMessage());
            }

        } catch (IOException e) {
            System.out.println("Errore di input: " + e.getMessage());
        }
    }
    
    /**
     * Inserisce i record dal secondo in poi
     */
    
    private void otherInsert(){
        //Objects
        datainventory   = new DataInventory();
        //tmp             = new DataInventory();
        temp = new DataInventory[count()];
        int i       = 0;
        int size    = count();
        
        //Vars
        String name         = new String();
        String description  = new String();
        String category     = new String();
        int quantity        = 0;
        int code            = code();
        
        //LETTURA
        try {
            fileInputStream   = new FileInputStream(FILE);
            objectInputStream = new ObjectInputStream(fileInputStream);
            
            //Leggo il file fino alla fine
            while(true){
                try{
                    //tmp = (DataInventory) objectInputStream.readObject();
                    temp[i] = (DataInventory) objectInputStream.readObject();
                    
                    i ++;
                }catch(EOFException e){
                    break;
                }
            }
            
            //objectInputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        
        //SCRITTURA
        try {
            input       = new InputStreamReader(System.in);
            tastiera    = new BufferedReader(input);
            
            //Read
            System.out.println("Nome: ");
            name = tastiera.readLine();
            System.out.println("Descrizione: ");
            description = tastiera.readLine();
            System.out.println("Categoria: ");
            category = tastiera.readLine();
            System.out.println("Quantita': ");
            quantity = Integer.valueOf(tastiera.readLine()).intValue();
            
            //Salvo i dati nella classe
            datainventory.addInventoryElement(name, description, category, quantity, code);
            
            //File
            try {
                fileOutputStream    = new FileOutputStream(FILE);
                objectOutputStream  = new ObjectOutputStream(fileOutputStream);
                
                //objectOutputStream.writeObject(tmp);
                for(int j = 0;j<i; j ++){
                    objectOutputStream.writeObject(temp[j]);
                }
                objectOutputStream.writeObject(datainventory);
                fileOutputStream.close();
            } catch (Exception e) {
                System.out.println("Errore nel salvataggio del record!");
            }
        } catch (Exception e) {
        }
    }
    
    /**
     * Visualizza l'inventario
     */
    public void show(){
        datainventory = new DataInventory();
        
        int cont = 0;
        
        try {
            fileInputStream   = new FileInputStream(FILE);
            objectInputStream = new ObjectInputStream(fileInputStream);
            
            while(true){
                try{
                    datainventory = (DataInventory) objectInputStream.readObject();

                    if(cont == 0){
                        System.out.println("=====================================");
                    }
                    
                    System.out.println("Codice: " + datainventory.code);
                    System.out.println("Nome: " + datainventory.name);
                    System.out.println("Descrizione: " + datainventory.description);
                    System.out.println("Categoria: " + datainventory.category);
                    System.out.println("Quantita': " + datainventory.quantity);
                    
                    System.out.println("=====================================");
                   
                    cont ++;
                }catch(EOFException e){
                    break;
                }
            }
            objectInputStream.close();
        } catch (Exception e) {
            System.out.println("Errore: " + e.getMessage());
        }
    }
    
    /**
     * Conta i record del file
     * 
     * @return Ritorna il numero di record
     */
    public int count(){
        datainventory = new DataInventory();
        int cont = 0;
        
        try {
            fileInputStream   = new FileInputStream(FILE);
            objectInputStream = new ObjectInputStream(fileInputStream);
            
            while(true){
                try{
                   datainventory = (DataInventory) objectInputStream.readObject();
                   
                   cont ++;
                }catch(EOFException e){
                    break;
                }
            }
            objectInputStream.close();
        } catch (Exception e) {}
        
        return cont;
    }
    
    
    /********************** SEARCH ***************************/
    
    
    /**
     * 
     */
    public void get(int a){
        int code = 0;
        input       = new InputStreamReader(System.in);
        tastiera    = new BufferedReader(input);
        
        if(a == 1){//By name
            String name = new String();
            
            System.out.println("\nRicerca in base al nome del prodotto");
            
            System.out.println("Nome: ");
            try {
                name = tastiera.readLine();
            } catch (Exception e) {}
            
            search(name);
        }else if(a == 2){//By Category
            String category = new String();
            
            System.out.println("\nRicerca in base alla categoria");
            
            System.out.println("Categoria: ");
            try {
                category = tastiera.readLine();
            } catch (Exception e) {}
            
            searchCategory(category);
        }else if(a == 3){//By code
            System.out.println("Ricerca in base al codice");
            try {
                code = Integer.valueOf(tastiera.readLine()).intValue();
            } catch (Exception e) {
                System.out.println("Errore nell'inserimento del codice");
                
                System.exit(1);//Blocco il programma
            }
            
            search(code);
        }
    }
    
    /**
     * Cerca in base al codice
     * @param code codice del record
     */
    private void search(int code){
        int cont = 0;
        
        try{
            FileInputStream f       = new FileInputStream("inventory.dat");
            ObjectInputStream fIN   = new ObjectInputStream(f);

            while (true) {                
                try {
                    datainventory = (DataInventory) fIN.readObject();
                    
                    //Se ho un riscontro
                    if(datainventory.code == code){
                        System.out.println("*************************************");
                        System.out.println("Codice:\t\t" + datainventory.code);
                        System.out.println("Nome:\t\t" + datainventory.name);
                        System.out.println("Descrizione:\t" + datainventory.description);
                        System.out.println("Categoria:\t" + datainventory.category);
                        System.out.println("Quantita':\t" + datainventory.quantity);
                        System.out.println("*************************************\n");
                        
                        cont ++;
                    }
                } catch (EOFException e) {
                    break;
                }
            }
            
            //Se non ho riscontri
            if(cont == 0){
                System.out.println("Nessun riscontro!");
            }

            f.close();
        }catch(Exception e){
            System.out.println("Eccezione: " + e.getMessage());
        }
    }
    /**
     * Ricerca in base al nome
     */
    private void search(String name){
        int cont = 0;
        
        try{
            FileInputStream f       = new FileInputStream("inventory.dat");
            ObjectInputStream fIN   = new ObjectInputStream(f);

            while (true) {                
                try {
                    datainventory = (DataInventory) fIN.readObject();
                    
                    //Converto tutto in minuscolo
                    datainventory.name = datainventory.name.toLowerCase();
                    
                    //Se ho un riscontro
                    if(datainventory.name.compareTo(name.toLowerCase()) == 0){
                        System.out.println("*************************************");
                        System.out.println("Codice:\t\t" + datainventory.code);
                        System.out.println("Nome:\t\t" + datainventory.name);
                        System.out.println("Descrizione:\t" + datainventory.description);
                        System.out.println("Categoria:\t" + datainventory.category);
                        System.out.println("Quantita':\t" + datainventory.quantity);
                        System.out.println("*************************************\n");
                        
                        cont ++;
                    }
                } catch (EOFException e) {
                    break;
                }
            }
            
            //Se non ho riscontri
            if(cont == 0){
                System.out.println("Nessun riscontro!");
            }

            f.close();
        }catch(Exception e){
            System.out.println("Eccezione: " + e.getMessage());
        }
    }
    
    /**
     * Ricerca in base alla categoria
     * @param name
     */
    private void searchCategory(String category){
        int cont = 0;
        
        try{
            FileInputStream f       = new FileInputStream("inventory.dat");
            ObjectInputStream fIN   = new ObjectInputStream(f);

            while (true) {                
                try {
                    datainventory = (DataInventory) fIN.readObject();

                    //Converto tutto in minuscolo
                    datainventory.category = datainventory.category.toLowerCase();
                    
                    //Se ho un riscontro
                    if(datainventory.category.compareTo(category) == 0){
                        System.out.println("*************************************");
                        System.out.println("Codice:\t\t" + datainventory.code);
                        System.out.println("Nome:\t\t" + datainventory.name);
                        System.out.println("Descrizione:\t" + datainventory.description);
                        System.out.println("Categoria:\t" + datainventory.category);
                        System.out.println("Quantita':\t" + datainventory.quantity);
                        System.out.println("*************************************\n");
                        
                        cont ++;
                    }
                } catch (EOFException e) {
                    break;
                }
            }
            
            //Se non ho riscontri
            if(cont == 0){
                System.out.println("Nessun riscontro!");
            }

            f.close();
        }catch(Exception e){
            System.out.println("Eccezione: " + e.getMessage());
        }
    }
}